package cron;


import api.FetchNeedChangePwdAccountList;
import api.FetchProxyIp;
import api.NoticeMessage;
import api.UpdateNeedChangePwdAccount;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import core.UpdatePassword;
import dao.AccountInfo;
import dao.ProxyConfig;
import dao.Result;
import main.MyStart;
import utils.LoggerUtile;

import java.util.*;



public class UpdateGareanPasswordTask {

     AccountInfo accountInfo = new AccountInfo();

    private  long startTime;

    int reportRetryCount;
    int retryCount;
    int proxyRetryCount;
    private  int proxyMaxRetry = 10;

    private  ProxyConfig proxyConfig = new ProxyConfig();

     String[] errorMessages = {
            "Proxy connection timed out",
            "Socks5 proxy rejected connection",
            "Socks5 Authentication failed",
            "timeout of 30000ms exceeded",
            "read ECONNRESET",
            "connect ECONNREFUSED",
            "Read timed out",
            "Host unreachable",
            "Malformed reply from SOCKS"
    };

     LoggerUtile logger;

    public  void updateGareanPasswordTask() {
        proxyRetryCount=1;
        reportRetryCount=0;
        retryCount=1;
        logger = LoggerUtile.getLogger("garenaJava-pwd-update");
        if (CronJob.taskList.get() >= 5) {
            try {
                Map md = new HashMap();
                md.put("businessType", "garenaChangePassword");
                md.put("content", "Garena自动改密执行的任务堆积过多 已堆积任务数量 :" + CronJob.taskList.get());
                md.put("msgTypeEnum", "TEXT");
                md.put("countryId", "251");
                NoticeMessage.noticeMessage(MyStart.addr_notify, JSON.toJSONString(md));
            } catch (Exception e) {
                if(e.getMessage().contains("Connection timed out")){
                    logger.info("告警服务超时！重新获取Nacos地址！");
                    MyStart.createNacosConnect();
                }
                logger.error("告警发送失败");
            }
        }

        if (CronJob.taskList.get()  > 6) {
            logger.info("当前执行中的任务过多 跳过本次查询 当前任务数 :", CronJob.taskList.get());
            return;
        }

        try {
            // 实现updateGareanPasswordTask的逻辑
            Map<String, Object> body = new HashMap<>();
            body.put("changePlatform", 1);
            body.put("pageNum", 1);
            body.put("pageSize", 1);
            body.put("javaChangePassword", 1);
            body.put("accessToken", MyStart.nacosConfig.get("accessToken"));
            body.put("gameIds", MyStart.garenaGameId.get("garenaGameId")); // Assuming config.getZingSpeedGameId() returns the appropriate data
            String s = JSON.toJSONString(body);
            String response = null;

            response = new FetchNeedChangePwdAccountList().fetchNeedChangePwdAccountList(MyStart.addr_security, s); //1nacos拿去账号信息

            logger.info("当前ip端口：" +MyStart.addr_security+" 加载garean改密任务列表结果" + response, "当前正在执行的任务数:" + CronJob.taskList.get());

            JSONObject parse = (JSONObject) JSONObject.parse(response);
            if (parse.get("data") == null) {
                return;
            }
            JSONObject data = (JSONObject) parse.get("data");
            JSONArray item = (JSONArray) data.get("item");
            if(item == null){
                return;
            }

            JSONObject accountInfo1 = (JSONObject) JSONObject.parse(JSON.toJSONString(item.get(0)));
            accountInfo.account = (String) accountInfo1.get("garenaAccount");
            accountInfo.password = (String) accountInfo1.get("garenaPassword");
            accountInfo.garenaAccount = (String) accountInfo1.get("garenaAccount");
            accountInfo.haoId = (String) accountInfo1.get("haoId");
            accountInfo.orderId = (String) accountInfo1.get("orderId");
            accountInfo.garenaKey = (String) accountInfo1.get("garenaKey");
            accountInfo.insertTime = System.currentTimeMillis();
            CronJob.taskList.getAndAdd(1) ;
            //   if ("prod".equals(env)){
            fetchProxy(null); //2查找代理
            //  }else {
            //       updatePassword();
            //   }
        } catch (Exception e) {
            logger.error("加载garean改密任务列表结果失败：" + e+"当前ip端口：" +MyStart.addr_security);
            //重新发布导致无数据
            if(e.getMessage().contains("timed out")){
                logger.info("重新获取Nacos地址！");
                MyStart.createNacosConnect();
            }
        }

    }

     void updatePassword() {
         long nowt = System.currentTimeMillis();
         startTime = System.currentTimeMillis();
         logger.info("开始第" + retryCount + "次改密任务,当前改密任务数量："+CronJob.taskList.get());
         logger.info("改密前账号信息：" + JSON.toJSONString(accountInfo));
         logger.info("改密码前：" + accountInfo.getAccount() +" 密码：" +accountInfo.getPassword());
         UpdatePassword updatePassword = new UpdatePassword();
         //子流程(具体改密的)
         Result result = updatePassword.start(accountInfo,proxyConfig, 0, MyStart.addr_security, MyStart.addr_gamecenter);
        try {
            logger.info("第" + retryCount + "次改密任务完成" + JSON.toJSONString(result));
            retryCount++;
            logger.info("改密耗时" + (System.currentTimeMillis() - nowt));
            //第4次改密任务完成{"code":33,"data":{"id":"1699948818037","error":"error_auth"},"msg":"登录异常参数或密码错误"}

            int code = result.getCode();
            // 验证码无法解决 或 HTTP异常
            if ((code == 11 || code == -1) && retryCount < 10) {
                String msg = result.getMsg();
                if(msg!=null && msg.contains("需要验证")){
                    logger.info("代理失效重新获取代理：" + proxyConfig.getIp());
                    fetchProxy(proxyConfig.getIp());
                    return;
                }
                String error = (String) result.getData();
                if (error != null) {
                    for (String errorMessage : errorMessages) {
                        if(error.contains(errorMessage)){
                            logger.info("代理IP异常" + proxyConfig.getIp());
                            fetchProxy(proxyConfig.getIp());
                            return;
                        }
                    }
                }
                logger.info("连接异常重试 次数：" + retryCount);
                fetchProxy(proxyConfig.getIp());
                return;
            }
        } catch (Exception e) {
            //CronJob.taskList.getAndAdd(-1);
            logger.error("任务处理异常" + e+",当前改密任务数量："+CronJob.taskList.get());
        }
         handleCompleted(result);
    }

     void fetchProxy(String dsip) {
        try {
            Map<String, Object> body = new HashMap<>();
            body.put("proxyType", 1);
            body.put("disableIp", (dsip != null ? dsip : null));
            String response = FetchProxyIp.fetchProxyIp(MyStart.addr_security, JSON.toJSONString(body));
            logger.info("代理查询结果" + response);
            JSONObject jsonObject = JSONObject.parseObject(response);
            proxyConfig.setIp(jsonObject.getJSONObject("data").getString("ip"));
            proxyConfig.setPort(Integer.valueOf(jsonObject.getJSONObject("data").getString("port")));
            updatePassword();//3改密
        } catch (Exception e) {
            // 代理查询请求异常重试
            if (proxyRetryCount < proxyMaxRetry) {
                logger.info("代理IP查询失败,稍后重试" + e.getMessage() + " 当前第" +proxyRetryCount + "次");
                proxyRetryCount++;
                fetchProxy(null);
                return;
            }
            logger.info("代理IP查询失败,重试结束" + e);
            handleCompleted(new Result(-1, "代理IP查询异常", e));
        }
    }

    public  void handleCompleted(Result result) {
        try {
            String garenaAccount = accountInfo.getGarenaAccount();
            String haoId = accountInfo.getHaoId();
            String orderId = accountInfo.getOrderId();
//            for (int i = 0; i < CronJob.taskList; i++) {
//                AccountInfo accountInfo1 = CronJob.taskList.get(i);
//                if (accountInfo1.getOrderId().equals(orderId)) {
//                    CronJob.taskList.remove(i);
//                    break; // 退出循环，因为已找到匹配项
//                }
//            }
            Map<String, Object> formData = new HashMap<>();
            formData.put("changePlatform", 1);
            formData.put("garenaAccount", garenaAccount);
            formData.put("haoId", haoId);
            formData.put("orderId", orderId);
            int code = result.getCode();
            String message =result.getMsg();
            Object data =  result.getData();
            String nowPassword = "";
            if (code == 0) {
                JSONObject Jdata = (JSONObject) JSONObject.parse((String) data);
                nowPassword = (String) Jdata.get("nowPassword");
            }

            formData.put("status", code == 0 ? 10 : 20);
            formData.put("handleErrorCode", 4); // 4-默认 验证异常 网络异常等
            formData.put("garenaPassword", code == 0 ? nowPassword : null);
            formData.put("handleOriginalMsg", message);
            formData.put("accessToken", "5ad9ba4e4a18d81457c3a8286e134f05");


            if (code >= 20 && code < 30) formData.put("handleErrorCode", 3); // 账号无效/密码未知/key未知
            if (code >= 30 && code < 40 || code == -3)
                formData.put("handleErrorCode", 6); // 账号有效/密码无效/key未知 -3表示通过缓存session无法修改
            if (code >= 60 && code < 70) formData.put("handleErrorCode", 7); // 账号有效/密码有效/key无效
            if (code == 0) formData.put("handleErrorCode", 5); // 账号/密码/key都有效
            String s = "";
            try {
                s = UpdateNeedChangePwdAccount.updateNeedChangePwdAccount(MyStart.addr_security, JSON.toJSONString(formData));
            } catch (Exception e) {

            }
            logger.info("更新改密结果完成" + s);
            CronJob.taskList.getAndAdd(-1);
            logger.info("改密任务全程耗时" + (System.currentTimeMillis() - startTime)+",当前改密任务数量："+CronJob.taskList.get());
        } catch (Exception error) {
            logger.error("更新改密结果请求异常,一分钟后重试" + error);
            reportRetryCount = reportRetryCount + 1;
            if (reportRetryCount >= 3) return;
            // 一分钟后重试 重试3次
            scheduleRetry(result, 60 * 1000);
        }
    }

    public  void scheduleRetry(Result result, long delay) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handleCompleted(result);
            }
        }, delay);
    }

}

